package com.example.bumenguanli.Filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
@Component
public class RequestLogFilter implements Filter {

    private static final Logger log = LoggerFactory.getLogger(RequestLogFilter.class);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String requestURI = httpRequest.getRequestURI();
        String ip = httpRequest.getRemoteAddr();

        // 记录请求开始
        Instant start = Instant.now();
        log.info("➡➡️ 收到请求：{} {} 来自 IP：{}", httpRequest.getMethod(), requestURI, ip);

        try {
            // 继续处理请求
            chain.doFilter(request, response);
        } finally {
            // 记录请求结束
            Instant end = Instant.now();
            long duration = Duration.between(start, end).toMillis();
            log.info("⬅⬅️ 请求结束：{} {} | 耗时：{} ms", httpRequest.getMethod(), requestURI, duration);
        }
    }
}